package im.zhihao.zhdisk.module.link.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.http.ContentType;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import im.zhihao.zhdisk.core.exception.IllegalDownloadLinkException;
import im.zhihao.zhdisk.core.util.AjaxJson;
import im.zhihao.zhdisk.core.util.StringUtils;
import im.zhihao.zhdisk.module.config.model.dto.SystemConfigDTO;
import im.zhihao.zhdisk.module.config.service.SystemConfigService;
import im.zhihao.zhdisk.module.link.model.entity.ShortLink;
import im.zhihao.zhdisk.module.link.model.entity.UserShortLink;
import im.zhihao.zhdisk.module.link.model.request.BatchGenerateLinkRequest;
import im.zhihao.zhdisk.module.link.model.result.BatchGenerateLinkResponse;
import im.zhihao.zhdisk.module.link.service.LinkDownloadService;
import im.zhihao.zhdisk.module.link.service.ShortLinkService;
import im.zhihao.zhdisk.module.storage.service.StorageSourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.internal.resource.filesystem.FileSystemResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.*;

/**
 * 短链接口
 *
 * @author zhihao
 */
@Controller
@Slf4j
public class ShortLinkController {

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private ShortLinkService shortLinkService;

    @Resource
    private StorageSourceService storageSourceService;

    @Resource
    private LinkDownloadService linkDownloadService;

    @Value("${oss.homomorphism.server}")
    private String homomorphismServerUrl;

    @PostMapping("/api/short-link/batch/generate")
    @ResponseBody
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "生成短链", notes = "对指定存储源的某文件路径生成短链")
    public AjaxJson<List<BatchGenerateLinkResponse>> generatorShortLink(@RequestBody @Valid BatchGenerateLinkRequest batchGenerateLinkRequest) {
        List<BatchGenerateLinkResponse> result = new ArrayList<>();
        String strLoginId = StpUtil.getLoginId().toString();
        Integer userId = null;
        if (!strLoginId.equals("admin")){
            userId = Integer.parseInt(strLoginId);
        }
        // 获取站点域名
        SystemConfigDTO systemConfig = systemConfigService.getSystemConfig();

        // 是否允许使用短链和短链，如果都不允许，则提示禁止生成.
        Boolean showShortLink = systemConfig.getShowShortLink();
        Boolean showPathLink = systemConfig.getShowPathLink();
        if ( BooleanUtil.isFalse(showShortLink) && BooleanUtil.isFalse(showPathLink)) {
            throw new IllegalDownloadLinkException("当前系统不允许使用直链和短链.");
        }

        String domain = systemConfig.getDomain();
        Long expireTime = batchGenerateLinkRequest.getExpireTime();
        String storageKey = batchGenerateLinkRequest.getStorageKey();
        Integer storageId = storageSourceService.findIdByKey(storageKey, userId);
        String encryType = batchGenerateLinkRequest.getEncryType();

        for (String path : batchGenerateLinkRequest.getPaths()) {
            // 拼接全路径地址.
            String fullPath = StringUtils.concat(path);
            ShortLink shortLink = shortLinkService.generatorShortLink(storageId, fullPath, expireTime, encryType);
            String shortUrl = StringUtils.removeDuplicateSlashes(domain + "/s/" + shortLink.getShortKey());
            String pathLink = StringUtils.generatorPathLink(storageKey, fullPath);
            result.add(new BatchGenerateLinkResponse(shortUrl, pathLink));
            sendUploadPost(storageKey, fullPath, encryType, shortLink.getShortKey());
        }
        return AjaxJson.getSuccessData(result);
    }

    public void sendUploadPost(String storageKey, String filePath, String encryType, String shortKey){
//        String url = "http://your-python-server/upload"; // 替换为你的接口地址
        byte[] contentBytes = linkDownloadService.handlerDownloadFile(storageKey, filePath);
        System.out.println(contentBytes.length);
        RestTemplate restTemplate = new RestTemplate();

        // 1. 创建 HttpHeaders
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Encry-Type", encryType); // 可选：添加自定义请求头

        ByteArrayResource resource = new ByteArrayResource(contentBytes) {
            @Override
            public String getFilename() {
                return shortKey; // 设置给后端看的文件名，必须！
            }
        };

        // 2. 创建请求体部分（文件）
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", resource); // "file" 要和后端 Flask 里的字段名对应

        // 3. 组装请求体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 4. 发送 POST 请求
        ResponseEntity<String> response = restTemplate.postForEntity(homomorphismServerUrl+"/oss/upload", requestEntity, String.class);

        // 5. 输出结果
        System.out.println("响应状态：" + response.getStatusCode());
        System.out.println("响应内容：" + response.getBody());
    }


    @GetMapping("/s/{key}")
    @ResponseStatus(HttpStatus.FOUND)
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "跳转短链", notes = "根据短链 key 跳转（302 重定向）到对应的直链.")
    @ApiImplicitParam(paramType = "path", name = "key", value = "短链 key", required = true, dataTypeClass = String.class)
    public void parseShortKey(@PathVariable String key) throws IOException {
        linkDownloadService.handlerShortLink(key);
    }
}